package com.example.admin.service.impl;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.admin.entity.SysPermission;
import com.example.admin.entity.SysRole;
import com.example.admin.entity.SysRolePermission;
import com.example.admin.entity.SysUser;
import com.example.admin.mapper.SysPermissionMapper;
import com.example.admin.service.ISysPermissionService;
import com.example.admin.service.ISysRolePermissionService;
import com.example.admin.service.ISysRoleService;

/**
 * <p>
 * 资源权限信息表 服务实现类
 * </p>
 *
 * @author wangkai
 * @since 2019-06-04
 */
@Service("sysPermissionService")
public class SysPermissionServiceImpl extends ServiceImpl<SysPermissionMapper, SysPermission>
		implements ISysPermissionService {

	@Resource(name = "sysRolePermissionService")
	private ISysRolePermissionService rpService;

	@Resource(name = "sysRoleService")
	private ISysRoleService roleService;

	@Override
	@Transactional(readOnly = false, rollbackFor = { Exception.class, RuntimeException.class })
	public boolean deleteParmission(SysPermission permission) {
		QueryWrapper<SysRolePermission> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("resource_id", permission.getId());
		if (rpService.remove(queryWrapper)) {
			if (!permission.deleteById()) {
				throw new RuntimeException();
			}
		} else {
			throw new RuntimeException();
		}
		return true;
	}

	@Override
	public List<SysPermission> getUserList(SysUser sysUser) {
		List<SysRole> list = roleService.getRoleList(sysUser.getId());
		List<SysPermission> result = new ArrayList<>();
		for (SysRole sysRole : list) {
			if (sysRole.getPermissions() != null && sysRole.getPermissions().size() > 0) {
				result.addAll(sysRole.getPermissions());
			}
		}
		return result;
	}

}
